<template>
  <div class="login-container">
    <div class="login-box">
      <!-- 登录/注册标签切换 -->
      <div class="tab-buttons">
        <button 
          :class="{ active: activeTab === 'login' }" 
          @click="activeTab = 'login'"
        >
          登录
        </button>
        <button 
          :class="{ active: activeTab === 'register' }" 
          @click="activeTab = 'register'"
        >
          注册
        </button>
      </div>

      <!-- 登录表单 -->
      <form v-if="activeTab === 'login'" @submit.prevent="handleLogin">
        <h2>用户登录</h2>
        <div class="form-group">
          <label for="login-username">用户名:</label>
          <input 
            type="text" 
            id="login-username" 
            v-model="loginForm.username" 
            required 
            placeholder="请输入用户名"
            :disabled="loading"
          />
        </div>
        
        <div class="form-group">
          <label for="login-password">密码:</label>
          <input 
            type="password" 
            id="login-password" 
            v-model="loginForm.password" 
            required 
            placeholder="请输入密码"
            :disabled="loading"
          />
        </div>
        
        <button type="submit" :disabled="loading" class="login-button">
          {{ loading ? '登录中...' : '登录' }}
        </button>
        <div class="merchant-login-link">
          <a @click="goToMerchantLogin">商家登录</a>
        </div>
      </form>

      <!-- 注册表单 -->
      <form v-else @submit.prevent="handleRegister">
        <h2>用户注册</h2>
        <div class="form-group">
          <label for="register-username">用户名:</label>
          <input 
            type="text" 
            id="register-username" 
            v-model="registerForm.username" 
            required 
            placeholder="请输入用户名"
            :disabled="loading"
          />
        </div>
        
        <div class="form-group">
          <label for="register-password">密码:</label>
          <input 
            type="password" 
            id="register-password" 
            v-model="registerForm.password" 
            required 
            placeholder="请输入密码"
            :disabled="loading"
          />
        </div>
        
        <div class="form-group">
          <label for="confirm-password">确认密码:</label>
          <input 
            type="password" 
            id="confirm-password" 
            v-model="registerForm.confirmPassword" 
            required 
            placeholder="请再次输入密码"
            :disabled="loading"
          />
        </div>
        
        <button type="submit" :disabled="loading" class="register-button">
          {{ loading ? '注册中...' : '注册' }}
        </button>
      </form>

      <!-- 错误信息显示 -->
      <div v-if="errorMessage" class="error-message">
        {{ errorMessage }}
      </div>

      <!-- 成功信息显示 -->
      <div v-if="successMessage" class="success-message">
        {{ successMessage }}
      </div>
    </div>
  </div>
</template>

<script>
import axios from 'axios';
import { useStore } from 'vuex';
import { useRouter } from 'vue-router';

export default {
  name: 'Login',
  setup() {
    const store = useStore();
    const router = useRouter();
    
    return {
      store,
      router
    };
  },
  data() {
    return {
      activeTab: 'login', // 'login' 或 'register'
      loginForm: {
        username: '',
        password: ''
      },
      registerForm: {
        username: '',
        password: '',
        confirmPassword: ''
      },
      loading: false,
      errorMessage: '',
      successMessage: ''
    }
  },
  methods: {
    // 切换标签时重置消息
    resetMessages() {
      this.errorMessage = '';
      this.successMessage = '';
    },

    async handleLogin() {
      // 重置错误信息
      this.resetMessages();
      this.loading = true;
      
      try {
        // 发送登录请求到新的接口地址，使用代理路径
        const response = await axios.post('/api/user/login/login', {
          username: this.loginForm.username,
          password: this.loginForm.password
        });
        
        // 处理登录响应
        if (response.data.success) {
          // 保存用户信息和token到localStorage
          const userData = {
            userId: response.data.data.userId,
            username: response.data.data.username,
            token: response.data.data.token
          };
          
          localStorage.setItem('userInfo', JSON.stringify(userData));
          
          // 更新Vuex状态
          this.store.commit('user/updateUserInfo', {
            token: userData.token,
            username: userData.username,
            userId: userData.userId
          });
          
          // 跳转到首页
          this.router.push('/');
        } else {
          this.errorMessage = response.data.message || '登录失败';
        }
      } catch (error) {
        console.error('登录错误:', error);
        this.errorMessage = '登录失败，请检查用户名和密码';
      } finally {
        this.loading = false;
      }
    },

    async handleRegister() {
      // 重置消息
      this.resetMessages();
      
      // 验证密码一致性
      if (this.registerForm.password !== this.registerForm.confirmPassword) {
        this.errorMessage = '两次输入的密码不一致';
        return;
      }

      this.loading = true;
      
      try {
        // 发送注册请求到新的接口地址，使用代理路径
        const response = await axios.post('/api/user/login/register', {
          username: this.registerForm.username,
          password: this.registerForm.password
        });
        
        // 处理注册响应
        if (response.data.success) {
          this.successMessage = '注册成功';
          // 自动切换到登录标签
          setTimeout(() => {
            this.activeTab = 'login';
            // 填充用户名
            this.loginForm.username = this.registerForm.username;
          }, 1000);
        } else {
          this.errorMessage = response.data.message || '注册失败';
        }
      } catch (error) {
        console.error('注册错误:', error);
        this.errorMessage = '注册失败，请稍后重试';
      } finally {
        this.loading = false;
      }
    },
    
    goToMerchantLogin() {
      // 跳转到商家登录页面
      this.router.push('/merchant-login');
    }
  }
}
</script>

<style lang="less" scoped>
.login-container {
  display: flex;
  justify-content: center;
  align-items: center;
  min-height: 500px;
  
  .login-box {
    width: 400px;
    padding: 30px;
    border-radius: 8px;
    box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
    border: 1px solid #e6e6e6;
    
    .tab-buttons {
      display: flex;
      margin-bottom: 20px;
      
      button {
        flex: 1;
        padding: 10px;
        border: none;
        background-color: #f5f5f5;
        cursor: pointer;
        transition: background-color 0.3s;
        
        &.active {
          background-color: #409eff;
          color: white;
        }
        
        &:first-child {
          border-top-left-radius: 4px;
          border-bottom-left-radius: 4px;
        }
        
        &:last-child {
          border-top-right-radius: 4px;
          border-bottom-right-radius: 4px;
        }
      }
    }
    
    h2 {
      text-align: center;
      margin-bottom: 30px;
      color: #333;
    }
    
    .form-group {
      margin-bottom: 20px;
      
      label {
        display: block;
        margin-bottom: 5px;
        color: #666;
      }
      
      input {
        width: 100%;
        padding: 12px;
        border: 1px solid #dcdfe6;
        border-radius: 4px;
        font-size: 14px;
        box-sizing: border-box;
        
        &:focus {
          outline: none;
          border-color: #409eff;
        }
        
        &:disabled {
          background-color: #f5f5f5;
          cursor: not-allowed;
        }
      }
    }
    
    .login-button, .register-button {
      width: 100%;
      padding: 12px;
      color: white;
      border: none;
      border-radius: 4px;
      font-size: 16px;
      cursor: pointer;
      
      &:hover:not(:disabled) {
        opacity: 0.9;
      }
      
      &:disabled {
        cursor: not-allowed;
      }
    }
    
    .login-button {
      background-color: #409eff;
    }
    
    .register-button {
      background-color: #409eff;
    }
    
    .merchant-login-link {
      text-align: right;
      margin-top: 10px;
      
      a {
        color: #409eff;
        cursor: pointer;
        text-decoration: none;
        
        &:hover {
          text-decoration: underline;
        }
      }
    }
    
    .error-message {
      margin-top: 15px;
      padding: 10px;
      background-color: #fef0f0;
      color: #f56c6c;
      border-radius: 4px;
      text-align: center;
    }
    
    .success-message {
      margin-top: 15px;
      padding: 10px;
      background-color: #f0f9ec;
      color: #67c23a;
      border-radius: 4px;
      text-align: center;
    }
  }
}
</style>